import os
from UserDb import UserDb
from CatalogDb import CatalogDb
from AccountDb import AccountDb
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import logging
  
def getUser():
    query = UserDb.all()
    return query.get()

def getUserById(userId):
    query = UserDb.all().filter('userId =', userId)
    return query.get()

def getUserWhenLogin(userName,userPwd):
    query =  UserDb.all()
    query.filter('userName =',userName).filter('userPassword =',userPwd)
    return query.get()

def clearCatalog():
    accountList = AccountDb.all()
    for account in accountList:
        account.delete()

    query = CatalogDb.all()
    for rs in query:
        rs.delete()
    return CatalogDb.all().count()

def deleteAccount(accountId):
    AccountDb.get_by_id(accountId).delete()

def deleteCatalog(catalogId):
    #delete all child catalogs of this catalog
    childCatalogList = CatalogDb.all().filter('catalogParent =',CatalogDb.get_by_id(catalogId))
    for child in childCatalogList:
        child.delete()
    #delete all account in this catalog
    accountList = AccountDb.all().filter('accountCatalog =',CatalogDb.get_by_id(catalogId))
    for account in accountList:
        account.delete()
        
    CatalogDb.get_by_id(catalogId).delete()


def clearUser():
    query = UserDb.all()
    for rs in query:
        rs.delete()
    return UserDb.all().count()
  
def getAllCatalog ():
    query = CatalogDb.all()
    return query

def getCatalog (catalogId):
    catalog = CatalogDb.get_by_id(catalogId)
    return catalog

def getAccountsByCatalog(catalog):
    query =  AccountDb.all()
    query.filter('accountCatalog =',catalog)
    return query 
      
def getAccount(keyId):
    account = AccountDb.get_by_id(keyId)
    return account


    
    
    